/**
 *
 */
package com.naiterui.ehp.bs.doctor.controller;

import com.naiterui.ehp.bp.constants.SwaggerTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bp.utils.qr.WeiXinEncrypUtil;
import com.naiterui.ehp.bs.doctor.exception.ExceptionCodes;
import com.naiterui.ehp.bs.doctor.service.IIndexService;
import com.naiterui.ehp.bs.doctor.service.IPAService;
import com.naiterui.ehp.bs.doctor.service.user.IDoctorAuthService;
import com.naiterui.ehp.bs.doctor.vo.SpreadAppVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @Description 认证通知
 */
@Api(tags = {SwaggerTag.DOCTOR + SwaggerTag.AUTH_RECORD})
@RequestMapping("ad/auth")
@Controller
public class AdDoctorAuthController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdDoctorAuthController.class);

    @Autowired
    private IPAService paService;
    @Autowired
    private IIndexService indexService;

    @Autowired
    private IDoctorAuthService doctorAuthService;


    /**
     * <h5页获取医生分享二维码数据> @param m 分享数据
     * @param k 分项数据md5
     * @return String <返回值描述>
     * @Throws 异常信息
     * @History 2015年11月12日 下午5:18:35 by chenlin
     */
    @ApiOperation(value = "h5页获取医生分享二维码数据", notes = "h5页获取医生分享二维码数据", httpMethod = "POST")
    @ApiImplicitParams({ @ApiImplicitParam(name = "m", value = "二维码密文数据，Base64([推广者id]:[推广类型])", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "k", value = "二维码原文数据md5签名", required = true, dataType = "string", paramType = "query") })
    @RequestMapping("getAppSpreadInfo")
    @ResponseBody
    public ResponseVO<SpreadAppVo> getAppSpreadInfo(String m, String k) throws BusinessException {

        LOGGER.info("h5页获取医生分享二维码数据 请求参数：m = [{}], k = [{}]", m, k);

        if (StringUtils.isEmpty(m) || StringUtils.isEmpty(k)) {
            LOGGER.error("h5页获取医生分享二维码数据为空:m=" + m + ",验证信息：k=" + k);
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        Long doctorId = null;
        int type = 0;
        try {
            // 验证通过
            if (!WeiXinEncrypUtil.md5Valid(m, k)) {
                LOGGER.error("请求h5页获取医生分享二维码数据证验失败，数据:m=" + m + ",验证信息：k=" + k);
                throw new BusinessException(ExceptionCodes.PARAM_ERROR);
            }
            String idType = WeiXinEncrypUtil.decryUrl(m);
            if (!StringUtils.isEmpty(idType)) {
                String[] arr = idType.split(":");

                doctorId = Long.parseLong(arr[0]);
                type = Integer.parseInt(arr[1]);
            }
            if (doctorId == null || type == 0) {
                LOGGER.error("请求h5页获取医生分享二维码数据证验失败，应该为数据修改:m=" + m + ",验证信息：k=" + k);
                throw new BusinessException(ExceptionCodes.PARAM_ERROR);
            }
        } catch (Exception e) {
            LOGGER.error("请求h5页获取医生分享二维码数据证验失败，应该为数据修改:m=" + m + ",验证信息：k=" + k, e);
            throw new BusinessException(ExceptionCodes.FAILED);
        }

        SpreadAppVo vo = null;
        try {
            vo = indexService.getAppSpreadInfo(doctorId, type);
        } catch (BusinessException e) {
            LOGGER.warn("h5页获取医生分享二维码数据业务异常 code:{} message:{}", e.getCode(), e.getMessage());
            throw new BusinessException(e.getCode());
        } catch (Exception e) {
            LOGGER.warn("h5页获取医生分享二维码数据异常 请求参数：m = [{}], k = [{}]", m, k, e);
            throw new BusinessException(ExceptionCodes.FAILED);
            // return PublicService.returnValue(ExceptionCodes.FAILED, vo);
        }
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, vo);

    }


    /**
     * @deprecated 接口迁移 {@link AdDoctorEsignUserController#realnameCode(java.lang.Long)}
     * <获取实名认证验证码>
     * @param doctorId
     * @return
     * @throws BusinessException
     */
    @Deprecated
    @ResponseBody
    @PostMapping("realname/code")
    @ApiOperation(value = "获取实名认证验证码（弃用）", notes = "见(医师电子签名用户设置) ad/esign/user", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorId", value = "医生id", required = true, dataType = "long") })
    public ResponseVO<Void> realnameCode(Long doctorId) throws BusinessException {

        LOGGER.info("获取实名认证验证码 请求参数：doctorId = [{}]", doctorId);

        doctorAuthService.getRealnameCode(doctorId);

        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);

    }

    /**
     * @deprecated {@link AdDoctorEsignUserController#realnameCheck(java.lang.Long, java.lang.String)}
     * <校验实名认证验证码>
     * @param doctorId
     * @return
     * @throws BusinessException
     */
    @Deprecated
    @ResponseBody
    @PostMapping("realname/check")
    @ApiOperation(value = "校验实名认证验证码（弃用）", notes = "见(医师电子签名用户设置) ad/esign/user", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorId", value = "医生id", required = true, dataType = "long"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "string") })
    public ResponseVO<Void> realnameCheck(Long doctorId, String code) throws BusinessException {

        LOGGER.info("验证实名认证验证码 请求参数：doctorId = [{}], code={}", doctorId, code);

        doctorAuthService.checkRealnameCode(doctorId, code);

        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);

    }

}
